package com.woniu.filter;

import com.woniu.config.MyLoginFailHandler;


import com.woniu.exception.TokenInvalidAuthentivationException;
import com.woniu.exception.TokenIsNullAuthenticationException;
import com.woniu.outlet.mapper.UserMapper;
import com.woniu.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MyLoginFailHandler failerHandler;

    @Override
    protected void doFilterInternal (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        if(requestURI.equals("/login")){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        String token = httpServletRequest.getHeader("token");
            if(StringUtils.isEmpty(token)){
//                ResponseResult responseResult = ResponseResult.error(ResultCode.TOKEN_IS_NULL);
//                httpServletResponse.setContentType("application/json;charset=utf-8");
//                PrintWriter out = httpServletResponse.getWriter();
//                out.write(new ObjectMapper().writeValueAsString(responseResult));
//                out.flush();
//                out.close();
                failerHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,
                        new TokenIsNullAuthenticationException("Token为空!"));
            }
        try {
            if(JwtTokenUtil.checkSign(token)){
                String userId = JwtTokenUtil.getUserId(token);
                List<String> preCodes = userMapper.getUserPercodeByUser(userId);
                ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                preCodes.forEach(preCode->{
                    grantedAuthorities.add(new SimpleGrantedAuthority(preCode));
                });
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId,"",grantedAuthorities));
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }
        } catch (Exception e) {
//              ResponseResult<String> fail = ResponseResult.error(ResultCode.TOKEN_INVALID_EXCEPTION);
//              httpServletResponse.setContentType("application/json;charset=utf-8");
//              PrintWriter out = httpServletResponse.getWriter();
//              out.write(new ObjectMapper().writeValueAsString(fail));
//              out.flush();
//              out.close();
//              return;
            e.printStackTrace();
            failerHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,
                    new TokenInvalidAuthentivationException("Token无效!"));
        }
    }
}
